<template>
  <div class="crm-customer">
    <el-card shadow="never">
      <template #header>
        <div class="crm-customer__header">
          <span>客户管理</span>
          <div>
            <el-button type="primary" size="small" @click="openCreate">新增</el-button>
            <el-button size="small" type="danger" :disabled="multipleSelection.length===0" @click="onBatchDelete">批量删除</el-button>
          </div>
        </div>
      </template>
      <el-form :inline="true" class="crm-customer__search" @submit.prevent>
        <el-form-item label="客户编码">
          <el-input v-model="query.customerCode" clearable placeholder="支持模糊" />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="query.customerName" clearable placeholder="支持模糊" />
        </el-form-item>
        <el-form-item label="客户类型">
          <el-select v-model="query.customerType" placeholder="全部" clearable>
            <el-option value="ENTERPRISE" label="企业" />
            <el-option value="INDIVIDUAL" label="个人" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户分类">
          <el-select v-model="query.categoryId" clearable filterable placeholder="请选择分类" style="width: 200px">
            <el-option
              v-for="cat in categoryOptions"
              :key="cat.categoryId"
              :label="cat.categoryName"
              :value="String(cat.categoryId)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户等级">
          <el-select v-model="query.levelId" clearable filterable placeholder="请选择等级" style="width: 200px">
            <el-option
              v-for="level in levelOptions"
              :key="level.levelId"
              :label="level.levelName"
              :value="String(level.levelId)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="query.status" placeholder="全部" clearable>
            <el-option :value="1" label="启用" />
            <el-option :value="0" label="停用" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户来源">
          <el-input v-model="query.source" clearable placeholder="支持模糊" />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="query.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始"
            end-placeholder="结束"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="onSearch">查询</el-button>
          <el-button size="small" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="list" size="small" style="width: 100%" @selection-change="onSelectionChange">
        <el-table-column type="selection" width="48" />
        <el-table-column prop="customerCode" label="客户编码" min-width="120" />
        <el-table-column prop="customerName" label="客户名称" min-width="160" />
        <el-table-column prop="customerType" label="客户类型" min-width="100">
          <template #default="{ row }">
            <el-tag v-if="row.customerType === 'ENTERPRISE'" type="primary">企业</el-tag>
            <el-tag v-else-if="row.customerType === 'INDIVIDUAL'" type="info">个人</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="industry" label="所属行业" min-width="120" />
        <el-table-column prop="phone" label="联系电话" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="160" />
        <el-table-column prop="city" label="城市" min-width="100" />
        <el-table-column prop="status" label="状态" min-width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">{{ row.status === 1 ? '启用' : '停用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="客户来源" min-width="120" />
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="openEdit(row)">编辑</el-button>
            <el-popconfirm title="确认删除该客户？" @confirm="onDelete(row)">
              <template #reference>
                <el-button link type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="crm-customer__pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :current-page="pageNum"
          @size-change="onSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>

    <el-drawer v-model="drawerVisible" :with-header="true" :title="drawerTitle" size="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="客户编码" prop="customerCode">
          <el-input v-model="form.customerCode" maxlength="64" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="form.customerName" maxlength="200" />
        </el-form-item>
        <el-form-item label="客户类型" prop="customerType">
          <el-select v-model="form.customerType" placeholder="请选择" style="width: 100%">
            <el-option value="ENTERPRISE" label="企业" />
            <el-option value="INDIVIDUAL" label="个人" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户分类" prop="categoryId">
          <el-select v-model="form.categoryId" clearable filterable placeholder="请选择分类" style="width: 100%">
            <el-option
              v-for="cat in categoryOptions"
              :key="cat.categoryId"
              :label="cat.categoryName"
              :value="String(cat.categoryId)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户等级" prop="levelId">
          <el-select v-model="form.levelId" clearable filterable placeholder="请选择等级" style="width: 100%">
            <el-option
              v-for="level in levelOptions"
              :key="level.levelId"
              :label="level.levelName"
              :value="String(level.levelId)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属行业" prop="industry">
          <el-input v-model="form.industry" maxlength="100" />
        </el-form-item>
        <el-form-item label="法人代表" prop="legalPerson">
          <el-input v-model="form.legalPerson" maxlength="64" />
        </el-form-item>
        <el-form-item label="注册资本" prop="registeredCapital">
          <el-input-number v-model="form.registeredCapital" :precision="2" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="creditCode">
          <el-input v-model="form.creditCode" maxlength="64" />
        </el-form-item>
        <el-form-item label="税务登记号" prop="taxNumber">
          <el-input v-model="form.taxNumber" maxlength="64" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" maxlength="32" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" maxlength="128" />
        </el-form-item>
        <el-form-item label="网站" prop="website">
          <el-input v-model="form.website" maxlength="200" />
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-input v-model="form.province" maxlength="64" />
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="form.city" maxlength="64" />
        </el-form-item>
        <el-form-item label="区县" prop="district">
          <el-input v-model="form.district" maxlength="64" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" type="textarea" :rows="2" maxlength="500" />
        </el-form-item>
        <el-form-item label="邮编" prop="postalCode">
          <el-input v-model="form.postalCode" maxlength="16" />
        </el-form-item>
        <el-form-item label="开户银行" prop="bankName">
          <el-input v-model="form.bankName" maxlength="128" />
        </el-form-item>
        <el-form-item label="银行账号" prop="bankAccount">
          <el-input v-model="form.bankAccount" maxlength="64" />
        </el-form-item>
        <el-form-item label="客户来源" prop="source">
          <el-input v-model="form.source" maxlength="32" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择" style="width: 100%">
            <el-option :value="1" label="启用" />
            <el-option :value="0" label="停用" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: 1; text-align: center">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">保存</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import {
  pageCustomer,
  createCustomer,
  updateCustomer,
  getCustomer,
  deleteCustomer,
  deleteCustomerBatch
} from '@/api/crm/customer'
import { getCustomerCategoryTree, listCustomerLevel } from '@/api/crm/customer'
import { ElMessage } from 'element-plus'

interface CustomerForm {
  customerId?: string
  customerCode: string
  customerName: string
  customerType: 'ENTERPRISE' | 'INDIVIDUAL'
  categoryId?: string
  levelId?: string
  industry?: string
  legalPerson?: string
  registeredCapital?: number
  creditCode?: string
  taxNumber?: string
  phone?: string
  email?: string
  website?: string
  address?: string
  province?: string
  city?: string
  district?: string
  postalCode?: string
  bankName?: string
  bankAccount?: string
  ownerUserId?: string
  ownerDeptId?: string
  status: number
  source?: string
  remark?: string
}

const list = ref<any[]>([])
const tableRef = ref()
const selectedIds = ref<Set<string>>(new Set())
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const query = reactive<{
  customerCode?: string
  customerName?: string
  customerType?: string
  categoryId?: string
  levelId?: string
  status?: number | ''
  source?: string
  timeRange?: string[]
}>({
  customerCode: '',
  customerName: '',
  customerType: '',
  categoryId: '',
  levelId: '',
  status: '',
  source: '',
  timeRange: []
})
const multipleSelection = ref<any[]>([])

const drawerVisible = ref(false)
const isEdit = ref(false)
const drawerTitle = ref('新增客户')
const formRef = ref<FormInstance>()
const form = reactive<CustomerForm>({
  customerCode: '',
  customerName: '',
  customerType: 'ENTERPRISE',
  categoryId: '',
  levelId: '',
  industry: '',
  legalPerson: '',
  registeredCapital: undefined,
  creditCode: '',
  taxNumber: '',
  phone: '',
  email: '',
  website: '',
  address: '',
  province: '',
  city: '',
  district: '',
  postalCode: '',
  bankName: '',
  bankAccount: '',
  ownerUserId: '',
  ownerDeptId: '',
  status: 1,
  source: '',
  remark: ''
})
const rules: FormRules = {
  customerCode: [{ required: true, message: '请输入客户编码', trigger: 'blur' }],
  customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  customerType: [{ required: true, message: '请选择客户类型', trigger: 'change' }]
}
const submitLoading = ref(false)

// 下拉选项
const categoryOptions = ref<any[]>([])
const levelOptions = ref<any[]>([])

const loadCategoryOptions = async () => {
  try {
    const res = await getCustomerCategoryTree('1')
    categoryOptions.value = res?.data || []
  } catch (error) {
    console.error('加载客户分类失败:', error)
  }
}

const loadLevelOptions = async () => {
  try {
    const res = await listCustomerLevel('1')
    levelOptions.value = res?.data || []
  } catch (error) {
    console.error('加载客户等级失败:', error)
  }
}

const load = async () => {
  const res = await pageCustomer({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    customerCode: query.customerCode || undefined,
    customerName: query.customerName || undefined,
    customerType: query.customerType || undefined,
    categoryId: query.categoryId || undefined,
    levelId: query.levelId || undefined,
    status: query.status === '' ? undefined : String(query.status),
    source: query.source || undefined,
    startTime:
      Array.isArray(query.timeRange) && query.timeRange.length === 2 ? query.timeRange[0] : undefined,
    endTime:
      Array.isArray(query.timeRange) && query.timeRange.length === 2 ? query.timeRange[1] : undefined
  })
  list.value = res?.data?.records || []
  total.value = res?.data?.total || 0
}

const onPageChange = (p: number) => {
  pageNum.value = p
  load()
}
const onSizeChange = (s: number) => {
  pageSize.value = s
  pageNum.value = 1
  load()
}

const onSearch = () => {
  pageNum.value = 1
  load()
}

const onReset = () => {
  query.customerCode = ''
  query.customerName = ''
  query.customerType = ''
  query.categoryId = ''
  query.levelId = ''
  query.status = ''
  query.source = ''
  query.timeRange = []
  onSearch()
}

const resetForm = () => {
  form.customerId = undefined
  form.customerCode = ''
  form.customerName = ''
  form.customerType = 'ENTERPRISE'
  form.categoryId = ''
  form.levelId = ''
  form.industry = ''
  form.legalPerson = ''
  form.registeredCapital = undefined
  form.creditCode = ''
  form.taxNumber = ''
  form.phone = ''
  form.email = ''
  form.website = ''
  form.address = ''
  form.province = ''
  form.city = ''
  form.district = ''
  form.postalCode = ''
  form.bankName = ''
  form.bankAccount = ''
  form.ownerUserId = ''
  form.ownerDeptId = ''
  form.status = 1
  form.source = ''
  form.remark = ''
}

const openCreate = () => {
  isEdit.value = false
  drawerTitle.value = '新增客户'
  resetForm()
  drawerVisible.value = true
}

const openEdit = async (row: any) => {
  isEdit.value = true
  drawerTitle.value = '编辑客户'
  resetForm()
  try {
    const res = await getCustomer(String(row.customerId))
    const data = res?.data || {}
    Object.assign(form, {
      ...data,
      customerId: String(data.customerId),
      categoryId: data.categoryId ? String(data.categoryId) : '',
      levelId: data.levelId ? String(data.levelId) : '',
      ownerUserId: data.ownerUserId ? String(data.ownerUserId) : '',
      ownerDeptId: data.ownerDeptId ? String(data.ownerDeptId) : ''
    })
    drawerVisible.value = true
  } catch (error) {
    ElMessage.error('加载客户信息失败')
  }
}

const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const payload = {
          ...form,
          categoryId: form.categoryId ? Number(form.categoryId) : undefined,
          levelId: form.levelId ? Number(form.levelId) : undefined,
          ownerUserId: form.ownerUserId ? Number(form.ownerUserId) : undefined,
          ownerDeptId: form.ownerDeptId ? Number(form.ownerDeptId) : undefined
        }
        if (isEdit.value) {
          await updateCustomer(String(form.customerId!), payload as any)
          ElMessage.success('更新成功')
        } else {
          await createCustomer(payload as any)
          ElMessage.success('新增成功')
        }
        drawerVisible.value = false
        load()
      } catch (error: any) {
        ElMessage.error(error?.message || '保存失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const onDelete = async (row: any) => {
  try {
    await deleteCustomer(String(row.customerId))
    ElMessage.success('删除成功')
    load()
  } catch (error: any) {
    ElMessage.error(error?.message || '删除失败')
  }
}

const onBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  try {
    const ids = multipleSelection.value.map((row: any) => String(row.customerId))
    await deleteCustomerBatch(ids)
    ElMessage.success('批量删除成功')
    load()
  } catch (error: any) {
    ElMessage.error(error?.message || '批量删除失败')
  }
}

const onSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection
}

onMounted(() => {
  loadCategoryOptions()
  loadLevelOptions()
  load()
})
</script>

<style scoped lang="scss">
.crm-customer {
  &__header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  &__search {
    margin-bottom: 12px;
  }
  &__pagination {
    margin-top: 12px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

